<template>
  <div class="account-management-container">
    <div class="page-header">
      <h2>账号管理</h2>
      <p>在这里管理您的账号信息和安全设置</p>
    </div>
    
    <el-card class="main-card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basicInfo">
          <el-form 
            ref="basicInfoFormRef"
            :model="basicInfoForm" 
            :rules="basicInfoRules" 
            label-width="100px" 
            class="account-form"
          >
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="basicInfoForm.avatar" :src="basicInfoForm.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            
            <el-form-item label="用户名" prop="username">
              <el-input v-model="basicInfoForm.username" placeholder="请输入用户名" />
            </el-form-item>
            
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="basicInfoForm.nickname" placeholder="请输入昵称" />
            </el-form-item>
            
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="basicInfoForm.phone" placeholder="请输入手机号码" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="basicInfoForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitBasicInfo">保存修改</el-button>
              <el-button @click="resetBasicInfo">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="修改密码" name="password">
          <el-form 
            ref="passwordFormRef"
            :model="passwordForm" 
            :rules="passwordRules" 
            label-width="100px" 
            class="account-form"
          >
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input 
                v-model="passwordForm.currentPassword" 
                type="password" 
                placeholder="请输入当前密码" 
                show-password 
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="passwordForm.newPassword" 
                type="password" 
                placeholder="请输入新密码" 
                show-password 
              />
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input 
                v-model="passwordForm.confirmPassword" 
                type="password" 
                placeholder="请再次输入新密码" 
                show-password 
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitPasswordChange">修改密码</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="账号安全" name="security">
          <div class="security-list">
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">登录密码</div>
                <div class="security-desc">定期修改密码可以提高账号安全性</div>
              </div>
              <div class="security-action">
                <el-button type="primary" link @click="activeTab = 'password'">修改密码</el-button>
              </div>
            </div>
            
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">手机绑定</div>
                <div class="security-desc">已绑定手机：{{ maskPhone(basicInfoForm.phone) }}</div>
              </div>
              <div class="security-action">
                <el-button type="primary" link @click="showPhoneBindDialog">更换手机</el-button>
              </div>
            </div>
            
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">邮箱绑定</div>
                <div class="security-desc">已绑定邮箱：{{ maskEmail(basicInfoForm.email) }}</div>
              </div>
              <div class="security-action">
                <el-button type="primary" link @click="showEmailBindDialog">更换邮箱</el-button>
              </div>
            </div>
            
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">登录记录</div>
                <div class="security-desc">查看您的账号登录记录</div>
              </div>
              <div class="security-action">
                <el-button type="primary" link @click="showLoginRecords">查看记录</el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 修改手机号对话框 -->
    <el-dialog v-model="phoneDialogVisible" title="更换手机号" width="400px">
      <el-form :model="phoneForm" :rules="phoneRules" label-width="100px" ref="phoneFormRef">
        <el-form-item label="原手机号">
          <div>{{ maskPhone(basicInfoForm.phone) }}</div>
        </el-form-item>
        <el-form-item label="新手机号" prop="newPhone">
          <el-input v-model="phoneForm.newPhone" placeholder="请输入新手机号" />
        </el-form-item>
        <el-form-item label="验证码" prop="verificationCode">
          <div class="verification-code-container">
            <el-input v-model="phoneForm.verificationCode" placeholder="请输入验证码" />
            <el-button 
              type="primary" 
              :disabled="countdown > 0" 
              @click="sendVerificationCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重发` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="phoneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePhone">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 修改邮箱对话框 -->
    <el-dialog v-model="emailDialogVisible" title="更换邮箱" width="400px">
      <el-form :model="emailForm" :rules="emailRules" label-width="100px" ref="emailFormRef">
        <el-form-item label="原邮箱">
          <div>{{ maskEmail(basicInfoForm.email) }}</div>
        </el-form-item>
        <el-form-item label="新邮箱" prop="newEmail">
          <el-input v-model="emailForm.newEmail" placeholder="请输入新邮箱" />
        </el-form-item>
        <el-form-item label="验证码" prop="verificationCode">
          <div class="verification-code-container">
            <el-input v-model="emailForm.verificationCode" placeholder="请输入验证码" />
            <el-button 
              type="primary" 
              :disabled="emailCountdown > 0" 
              @click="sendEmailVerificationCode"
            >
              {{ emailCountdown > 0 ? `${emailCountdown}秒后重发` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="emailDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateEmail">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 登录记录对话框 -->
    <el-dialog v-model="loginRecordsVisible" title="登录记录" width="650px">
      <el-table :data="loginRecords" style="width: 100%" max-height="400">
        <el-table-column prop="time" label="登录时间" width="180" />
        <el-table-column prop="ip" label="IP地址" width="150" />
        <el-table-column prop="location" label="登录地点" />
        <el-table-column prop="device" label="设备" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'AccountManagement',
  components: {
    Plus
  },
  setup() {
    // 当前活动标签页
    const activeTab = ref('basicInfo')
    
    // 基本信息表单
    const basicInfoFormRef = ref(null)
    const basicInfoForm = reactive({
      avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      username: 'user123',
      nickname: '用户123',
      phone: '13800138000',
      email: 'user123@example.com'
    })
    
    const basicInfoRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ]
    }
    
    // 头像上传
    const handleAvatarSuccess = (res, file) => {
      basicInfoForm.avatar = URL.createObjectURL(file.raw)
      
      // 实际项目中这里应该先上传图片到服务器，然后再更新用户头像
      ElMessage.success('头像上传成功')
    }
    
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
      }
      
      return isJPG && isLt2M
    }
    
    // 提交基本信息
    const submitBasicInfo = () => {
      basicInfoFormRef.value.validate((valid) => {
        if (valid) {
          // 这里应该有API调用保存用户信息
          ElMessage.success('基本信息修改成功')
        } else {
          ElMessage.error('请填写正确的信息')
          return false
        }
      })
    }
    
    // 重置基本信息
    const resetBasicInfo = () => {
      basicInfoFormRef.value.resetFields()
    }
    
    // 密码修改表单
    const passwordFormRef = ref(null)
    const passwordForm = reactive({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        // 密码强度要求：至少8位，包含大小写字母和数字
        const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,20}$/
        if (!reg.test(value)) {
          callback(new Error('密码必须包含大小写字母和数字，且至少8位'))
        } else {
          if (passwordForm.confirmPassword !== '') {
            passwordFormRef.value.validateField('confirmPassword')
          }
          callback()
        }
      }
    }
    
    const validateConfirmPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    
    const passwordRules = {
      currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, validator: validatePass, trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, validator: validateConfirmPass, trigger: 'blur' }
      ]
    }
    
    // 提交密码修改
    const submitPasswordChange = () => {
      passwordFormRef.value.validate((valid) => {
        if (valid) {
          // 这里应该有API调用修改密码
          ElMessage.success('密码修改成功，请重新登录')
          // 清空表单
          resetPasswordForm()
        } else {
          ElMessage.error('请填写正确的信息')
          return false
        }
      })
    }
    
    // 重置密码表单
    const resetPasswordForm = () => {
      passwordFormRef.value.resetFields()
    }
    
    // 账号安全相关
    // 手机号掩码显示
    const maskPhone = (phone) => {
      if (!phone) return ''
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    }
    
    // 邮箱掩码显示
    const maskEmail = (email) => {
      if (!email) return ''
      const parts = email.split('@')
      if (parts.length !== 2) return email
      let name = parts[0]
      const domain = parts[1]
      if (name.length <= 2) {
        name = name.charAt(0) + '*' + (name.length > 1 ? name.charAt(name.length - 1) : '')
      } else {
        name = name.charAt(0) + '****' + name.charAt(name.length - 1)
      }
      return name + '@' + domain
    }
    
    // 修改手机号
    const phoneDialogVisible = ref(false)
    const phoneFormRef = ref(null)
    const phoneForm = reactive({
      newPhone: '',
      verificationCode: ''
    })
    const countdown = ref(0)
    
    const phoneRules = {
      newPhone: [
        { required: true, message: '请输入新手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      verificationCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
      ]
    }
    
    const showPhoneBindDialog = () => {
      phoneForm.newPhone = ''
      phoneForm.verificationCode = ''
      phoneDialogVisible.value = true
    }
    
    const sendVerificationCode = () => {
      if (!phoneForm.newPhone) {
        ElMessage.warning('请先输入新手机号')
        return
      }
      
      if (!/^1[3-9]\d{9}$/.test(phoneForm.newPhone)) {
        ElMessage.warning('请输入正确的手机号码')
        return
      }
      
      // 这里应该调用API发送验证码
      ElMessage.success(`验证码已发送至 ${phoneForm.newPhone}`)
      
      // 倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
    
    const updatePhone = () => {
      phoneFormRef.value.validate((valid) => {
        if (valid) {
          // 这里应该调用API更新手机号
          basicInfoForm.phone = phoneForm.newPhone
          ElMessage.success('手机号更新成功')
          phoneDialogVisible.value = false
        }
      })
    }
    
    // 修改邮箱
    const emailDialogVisible = ref(false)
    const emailFormRef = ref(null)
    const emailForm = reactive({
      newEmail: '',
      verificationCode: ''
    })
    const emailCountdown = ref(0)
    
    const emailRules = {
      newEmail: [
        { required: true, message: '请输入新邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      verificationCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
      ]
    }
    
    const showEmailBindDialog = () => {
      emailForm.newEmail = ''
      emailForm.verificationCode = ''
      emailDialogVisible.value = true
    }
    
    const sendEmailVerificationCode = () => {
      if (!emailForm.newEmail) {
        ElMessage.warning('请先输入新邮箱')
        return
      }
      
      // 这里应该调用API发送验证码
      ElMessage.success(`验证码已发送至 ${emailForm.newEmail}`)
      
      // 倒计时
      emailCountdown.value = 60
      const timer = setInterval(() => {
        emailCountdown.value--
        if (emailCountdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
    
    const updateEmail = () => {
      emailFormRef.value.validate((valid) => {
        if (valid) {
          // 这里应该调用API更新邮箱
          basicInfoForm.email = emailForm.newEmail
          ElMessage.success('邮箱更新成功')
          emailDialogVisible.value = false
        }
      })
    }
    
    // 登录记录
    const loginRecordsVisible = ref(false)
    const loginRecords = ref([
      {
        time: '2023-04-01 10:30:22',
        ip: '192.168.1.1',
        location: '北京市',
        device: 'Chrome / Windows 10',
        status: '成功'
      },
      {
        time: '2023-03-28 15:45:30',
        ip: '192.168.1.100',
        location: '北京市',
        device: 'Chrome / Windows 10',
        status: '成功'
      },
      {
        time: '2023-03-25 09:12:05',
        ip: '114.88.123.45',
        location: '上海市',
        device: 'Safari / iOS 15',
        status: '成功'
      },
      {
        time: '2023-03-20 18:30:45',
        ip: '220.181.38.148',
        location: '广州市',
        device: 'Firefox / Windows 11',
        status: '失败'
      }
    ])
    
    const showLoginRecords = () => {
      loginRecordsVisible.value = true
    }
    
    // 初始化
    onMounted(() => {
      // 可以在这里调用API获取用户信息
    })
    
    return {
      activeTab,
      basicInfoFormRef,
      basicInfoForm,
      basicInfoRules,
      handleAvatarSuccess,
      beforeAvatarUpload,
      submitBasicInfo,
      resetBasicInfo,
      
      passwordFormRef,
      passwordForm,
      passwordRules,
      submitPasswordChange,
      resetPasswordForm,
      
      maskPhone,
      maskEmail,
      
      phoneDialogVisible,
      phoneFormRef,
      phoneForm,
      phoneRules,
      countdown,
      showPhoneBindDialog,
      sendVerificationCode,
      updatePhone,
      
      emailDialogVisible,
      emailFormRef,
      emailForm,
      emailRules,
      emailCountdown,
      showEmailBindDialog,
      sendEmailVerificationCode,
      updateEmail,
      
      loginRecordsVisible,
      loginRecords,
      showLoginRecords
    }
  }
}
</script>

<style scoped>
.account-management-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 14px;
}

.main-card {
  margin-bottom: 24px;
}

.account-form {
  max-width: 500px;
  margin: 20px auto;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-radius: 50%;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
}

.security-list {
  max-width: 600px;
  margin: 20px auto;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.security-item:last-child {
  border-bottom: none;
}

.security-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 5px;
}

.security-desc {
  font-size: 14px;
  color: #666;
}

.verification-code-container {
  display: flex;
  gap: 10px;
}

.verification-code-container .el-input {
  flex: 1;
}
</style> 